package com.zs4sdk.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.common.library.data.CommonEventHandler;
import com.common.library.data.CommonHandle;
import com.common.library.data.EventHandler2Get;
import com.common.library.entity.JSONResultEntity;
import com.common.library.util.ActivityHelper;
import com.common.library.util.EncryptHelper;
import com.common.library.util.HandlerUtil;
import com.common.library.util.Helper;
import com.common.library.util.NetworkHelper;
import com.common.library.util.ParamsHelper;
import com.zs4sdk.common.Extra;
import com.zs4sdk.entity.LoginJSONResultEntity;
import com.zs4sdk.entity.Zs4GameData;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

/**
 * Created by Administrator on 2018/6/13.
 */

public class Zs4GameBindSafeAccountActivity extends Zs4GameBaseActivity {
    private int backSendMsg = 12;
    // 手机号码输入框
    private EditText mBindPhoneView;
    private EditText mBindPasswordView;
    private Button mBindConfirm;
    private TextView  tipTextView;

    private TextView mTxvUpdateDesc;
    @Override
    protected int getLeftBtnType() {

        if (getPackageName().concat(Extra.ACTIONKEY.CLOSEACTIVITY_POSTFIX_SLIDETOAST).equals(flag)) {
            return TYPE_LEFTBTN_BACKTOGAME;
        } else {
            return backSendMsg;
        }
    }

    @Override
    protected  int getRightBtnType() {
        return TYPE_RIGHTBTN_INVISIBLE;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(ActivityHelper.getLayoutResId("zs4gamelayout_act_bind_account"));

        getParams();
        init();
    }
    /**
     * 获取参数
     */
    private void getParams() {
        Intent intent = this.getIntent();

        if (Helper.isNotNull(intent)) {
            if (intent.hasExtra(Extra.INTENTKEY.BIND_PHONE)) {
                backSendMsg = TYPE_LEFTBTN_BACK;
            }else {
                backSendMsg =  TYPE_LEFTBTN_BACKTOMENU;
            }
        }

    }

    @Override
    protected void init() {
        super.init();

        //输入框部分
        mTxvUpdateDesc = findView(TextView.class, ActivityHelper.getIdResId("zs4gameviewid_mAccountView_act_txv_account"));//当前账号
        mBindPhoneView = findView(EditText.class, ActivityHelper.getIdResId("zs4gameviewid_mAccountView_act_bind_safe_phone"));//手机号输入框
        mBindPasswordView = findView(EditText.class, ActivityHelper.getIdResId("zs4gameviewid_mPasswordView_act_bind_safe_phone_password"));//密码输入框
        tipTextView = findView(TextView.class, ActivityHelper.getIdResId("zs4gameviewid_textview_retrivepassword_phone"));//点击按钮的提示信息
        mBindConfirm = findView(Button.class, ActivityHelper.getIdResId("zs4gameviewid_mCommitView_act_bind_safe_phone_confirm"));//确定
        setTopTitle(ActivityHelper.getStringResId("zs4gameAccountUpgrade"));
        mTxvUpdateDesc.setText( Zs4GameData.getInstance().getSDKUserInfo().getNickName());

        setViewClickEvent(this,
                ActivityHelper.getIdResId("zs4gameviewid_mCommitView_act_bind_safe_phone_confirm"));
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);

        int id = v.getId();
        // 确定绑定
        if (ActivityHelper.getIdResId("zs4gameviewid_mCommitView_act_bind_safe_phone_confirm") == id) {
            //更新的最后一步
            updateAccount();
        }
    }

    CommonHandle myHandle = new CommonHandle(this, new CommonHandle.HandleMessage() {

        @Override
        public void doHandleMessage(Message msg) {

       if (Extra.MessageKey.BIND_SAFE_PHONE_SUCCESS == msg.what) {

                LoginJSONResultEntity entity = new LoginJSONResultEntity((JSONObject) msg.obj);

                ActivityHelper.showLongToast(entity.getDesc());

                if (entity.isSuccess()) {

                    //返回手机号
                    Intent intent = new Intent();
//                    intent.putExtra(Extra.INTENTKEY.BIND_PHONE, mPhoneNum);
                    setResult(Extra.RESULTCODE.RESULT_BIND_PHONE, intent);
                    finish();
                }
            }
            //绑定结果
            else if (Extra.MessageKey.UPDATE_SAFE_PHONE_STEP_TWO == msg.what) {
                LoginJSONResultEntity entity = new LoginJSONResultEntity((JSONObject) msg.obj);

                if (entity.isSuccess()) {
                    LoginJSONResultEntity entity1 = Zs4GameData.getInstance().getLastLoginedUserInfo();
                    entity1.setLoginType("1");
                    Bundle bundle = msg.getData();
                    if (bundle.containsKey("param1")) {
                        entity1.setMobile(bundle.getString("param1"));
                    }
                    Zs4GameData.getInstance().saveUserLoginInfoForLoginedSuccess(entity1);
                    ActivityHelper.showToast(ActivityHelper.getStringResId("zs4gamestring_text_bind_successed"));
                    backToGame();
                }else {
                    tipTextView.setText(entity.getDesc());
                }
            }
        }
    });

    /***
     * 更新绑定安全手机，第二步 绑定
     */
    private void updateAccount() {
        final String account = mBindPhoneView.getText().toString().trim();
        String password =  mBindPasswordView.getText().toString().trim();
        String messageText = "";
        // 帐号不为空
        if (Helper.isEmpty(account)) {
            tipTextView.setText(ActivityHelper.getStringResId("zs4gamestring_hint_phone_num_format"));
            return;
        }//密码不能为空
        else if (Helper.isEmpty(password)) {
            tipTextView.setText(ActivityHelper.getStringResId("zs4gamestring_text_edt_tip_password"));
            return;
        }//密码长度错误
        else if (password.length() < 6||password.length()>12) {
            tipTextView.setText(ActivityHelper.getStringResId("zs4gamestring_hint_password_length"));
            return;
        }
        Log.e("phone"," bind phone is "+account);
        if (NetworkHelper.isNetworkAvailable(this)) {

            HandlerUtil.sendMessage(myHandle, Extra.MessageKey.SHOWPROCESS);

            ArrayList<NameValuePair> paramList = new ArrayList<NameValuePair>();
            //    paramList.add(new BasicNameValuePair("mobile", EncryptHelper.encryptByAES(phoneNumb)));
            paramList.add(new BasicNameValuePair("account", EncryptHelper.encryptByAES(account)));
            paramList.add(new BasicNameValuePair("password", EncryptHelper.encryptByAES(EncryptHelper.md5(password))));
            paramList.add(new BasicNameValuePair("is_useraccount","1"));
            paramList.add(new BasicNameValuePair("verifycode", EncryptHelper.encryptByAES(messageText)));
            //    Log.e("phone"," bind EncryptHelper.encryptByAES(phoneNumb)) is "+EncryptHelper.encryptByAES(phoneNumb));
            new EventHandler2Get(
                    Extra.URL.UPDATE_SAFE_PHONE,
                    paramList,
                    ParamsHelper.getUserAgent1(), new CommonEventHandler.ResultHandlerInEvent() {

                @Override
                public void doResultHanler(JSONObject result) throws JSONException {
                    HandlerUtil.sendMessage(myHandle, Extra.MessageKey.DISMISSPROCESS);
                    Log.e("phone"," phone result is "+result.toString());
                    Message msg = myHandle.obtainMessage();

                    msg.what = Extra.MessageKey.UPDATE_SAFE_PHONE_STEP_TWO;
                    msg.obj = result;

                    Bundle bundle = new Bundle();
                    bundle.putString("param1",account);
                    msg.setData(bundle);

                    // 发送消息
                    myHandle.sendMessage(msg);

                }

                @Override
                public void doExceptionHandler() {
                    HandlerUtil.sendMessage(myHandle, Extra.MessageKey.DISMISSPROCESS);
                }
            });
        }else {
            tipTextView.setText(ActivityHelper.getStringResId("zs4gamestring_hint_has_not_network"));
        }
    }
}
